import { defineStore } from 'pinia';

export const useClassStore = defineStore('class', {
  state: () => ({
    selectedClass: null,
    classList: [],
  }),
  getters: {
    classCount: (state) => state.classList.length,
  },
  actions: {
    selectClass(classData) {
      this.selectedClass = classData;
      localStorage.setItem('selectedClass', JSON.stringify(classData));
    },
    clearClass() {
      this.selectedClass = null;
      localStorage.removeItem('selectedClass');
    },
    async initializeClass() {
      const classData = localStorage.getItem('selectedClass');
      await this.fetchClassList();
      if (classData) {
        this.selectedClass = JSON.parse(classData);
      }else {
        if (this.classList.length > 0) {
          this.selectClass(this.classList[0]);
        }
      }
    },
    async fetchClassList() {
      const response = await window.electronAPI.getClassData();
      if (response.success) {
        this.classList = response.classes;
        if (!this.selectedClass && this.classList.length > 0) {
          this.selectClass(this.classList[0]);
        }
      } else {
        console.error('获取班级数据失败:', response.error);
      }
    },
    async addClass(classData) {
      const response = await window.electronAPI.saveClassData(classData);
      if (response.success) {
        await this.fetchClassList();
      } else {
        console.error('添加班级失败:', response.message || response.error);
      }
    },
    async deleteClass(classNo) {
      const response = await window.electronAPI.deleteClassData(classNo);
      if (response.success) {
        await this.fetchClassList(); 
        if (this.selectedClass && this.selectedClass.class_no === classNo) {
          if (this.classList.length > 0) {
            this.selectClass(this.classList[0]); 
          } else {
            this.clearClass();
          }
        }
      } else {
        console.error('删除班级失败:', response.message || response.error);
      }
    },
    async fetchStudentsByClassNo(classNo) {
      const response = await window.electronAPI.getStuDataByClassNo(classNo);
      if (response.success) {
        return response.students;
      } else {
        console.error('获取班级学生列表失败:', response.message || response.error);
        return [];
      }
    },
    async initializeClassList() {
      await this.fetchClassList();
    },
  },
});
